#include "medicinedelete.h"
#include "ui_medicinedelete.h"
#include <QMessageBox>

MedicineDeleteWindow::MedicineDeleteWindow(QWidget *parent)
    : QWidget(parent)
    , medicinedeletewindowUi(new Ui::MedicineDeleteWindow)
    , networkManager(new NetworkManager(this))
{
    medicinedeletewindowUi->setupUi(this);
    connect(networkManager, &NetworkManager::deleteMedicineResponseReceived, this, &MedicineDeleteWindow::handleDeleteMedicineResponse);
}

MedicineDeleteWindow::~MedicineDeleteWindow()
{
    delete medicinedeletewindowUi;
}

void MedicineDeleteWindow::on_deleteButton_clicked()
{
    QString name = medicinedeletewindowUi->nameLineEdit->text();

    if (name.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "请填写药品名称。");
        return;
    }

    QJsonObject json;
    json["name"] = name;

    networkManager->deleteMedicine(json);
}

void MedicineDeleteWindow::on_cancelButton_clicked()
{
    close();
}

void MedicineDeleteWindow::handleDeleteMedicineResponse(const QJsonObject &response)
{
    int code = response.value("code").toInt();
    QString desc = response.value("desc").toString();

    if (code == 200) {
        QMessageBox::information(this, "成功", "药品删除成功！");
        medicinedeletewindowUi->nameLineEdit->clear();  // Clear input field after successful deletion
    } else {
        QMessageBox::warning(this, "错误", "药品删除失败：" + desc);
    }
}
